var layer = require('layer');
var validate  = require('{plus}/validate');

Nui.doc.click(function(){
    layer.hide('position');
    layer.hide('die');
})

layer.die = function(e, elem, data, template, callback, options){
    e.stopPropagation();
    var position = function(){
        return {
            top:elem.offset().top,
            right:Nui.win.width() - (elem.offset().left + elem.outerWidth())
        }
    }
    return layer($.extend(true, {
        id:'die',
        template:'<div class=" e-pt10 e-pl20 e-pr20 e-pb10 f-lh20">'+template+'</div>',
        data:data,
        isMask:false,
        scrollbar:false,
        events:{
            'click':function(e){
                e.stopPropagation();
            }
        },
        button:[{
            id:'cancel',
            text:'取消'
        }, {
            id:'save',
            text:'确定',
            name:'normal',
            callback:callback
        }],
        position:position(),
        onResize:function(self){
            console.log(position())
            self.option(position, position())
        }
    }, options||{}));
}

layer.position = function(e, content, container, height, button, title, width, options){
    var dom = container.get(0);
    var top = 0;
    if(options && options.position && options.position.top){
        top = options.position.top;
        delete options.position.top
    }
    if(!dom.layer){
        layer.hide('position');
        dom.layer = layer($.extend(true, {
            content:content,
            id:'position',
            container:container,
            width:width,
            maxHeight:height,
            scrollbar:false,
            button:button,
            title:title,
            isMask:false,
            position:{
                right:0,
                top:container.height() + top
            },
            onDestroy:function(){
                delete dom.layer
            }
        }, options||{}))
    }
    e.stopPropagation()
    return dom.layer
}

layer.bubble = function(e, content, container, width, height, options){
    return layer.position(e, content, container, height, null, null, width, $.extend(true, {
        isTips:true,
        close:{
            enable:false
        },
        bubble:{
            enable:true,
            dir:'top'
        }
    }, options||{}))
}

layer.fullscreen = function(options){
    if(typeof options.initData === 'function'){
        options.initData()
    }
    options.data.isSuperlayer = true;
    return layer($.extend(true, options, {
        id:'fullscreen',
        isFull:true,
        title:null,
        cancel:{
            enable:false
        }
    }))
}

return layer